package main.strategy;

import configuration.RobConfiguration;
import main.robClass;
import mysql.MysqlUtil;
import robber.impl.CommonRobber;
import timer.saveCookieManager;
import timer.saveRobberManager;
import user.IUser;
import user.impl.robUser.RobUser;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static robber.RobberUtil.startRob;

//private Integer testTime;
public class StartCommonRobTimerStrategy implements RobStrategy {
    @Override
    public void execute(IUser user) {
        CommonRobber commonRobber = new CommonRobber(user);
        MysqlUtil.loadAbstractRobberData(commonRobber, user.getUsername());
        ScheduledExecutorService robTimerThread = Executors.newScheduledThreadPool(10);
        robTimerThread.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {

                /**抢课线程检测 1秒1次*/
        Date date = new Date();
                if (date.after(getStartTimeDate(user))) {
                    robClass.logger.info(this.getClass().getSimpleName() + "#已经超过了公选课时间,开始增加抢公选课线程!");
                    startRob(user, commonRobber);
                    try {
                        robTimerThread.shutdown();
                        robClass.logger.info(this.getClass().getSimpleName() + "#结束抢公选课定时器!");
                        if (!robTimerThread.awaitTermination(5000, TimeUnit.MILLISECONDS)) {
                            robTimerThread.shutdownNow();
                        }
                    } catch (InterruptedException e) {
                        robClass.logger.info("robTimerThread - awaitTermination interrupted: " + e);
                        robTimerThread.shutdownNow();
                    }
//                    this.cancel();
                }

            }
        }, 0, 1, TimeUnit.SECONDS);

        /**将用户信息写入数据库 12分钟一次*/
        ScheduledExecutorService saveResourcesThread = Executors.newScheduledThreadPool(10);
        saveResourcesThread.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                robClass.logger.info(this.getClass().getSimpleName() + "#" + user.getUsername() + "#" + user.getStudentName() + "#" + "定时抢公选课,每12分钟的预备资源检测:");
                Date date = new Date();
                Date startTime = getStartTimeDate(user);
                startTime.setTime(getStartTimeDate(user).getTime() - RobConfiguration.ROB_PRE_INIT_TIME_COURSE_PE);
                if (date.after(startTime)) {
                    robClass.logger.info("已经超过了抢公选课前6小时的时间,开始进行[写入]资源初始化!");
                    saveCookieManager.updateUserToGlobalIdAndCookies(user);
                    saveRobberManager.updateUserToGlobalIdAndRobberInfo(commonRobber);
                }
            }
        }, 2, 20, TimeUnit.SECONDS);


        /**预备资源检测 3分钟一次*/
        ScheduledExecutorService initResourcesThread = Executors.newScheduledThreadPool(30);
        initResourcesThread.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                robClass.logger.info(this.getClass().getSimpleName() + "#" + user.getUsername() + "#" + user.getStudentName() + "#" + "定时抢公选课,每3分钟的预备资源检测:");
                Date date = new Date();
                Date startTime = getStartTimeDate(user);
                startTime.setTime(getStartTimeDate(user).getTime() - RobConfiguration.ROB_PRE_INIT_TIME_COURSE_PE);
                if (date.after(startTime)) {
                    robClass.logger.info("已经超过了抢公选课前6小时的时间,开始进行资源初始化!");
//                    for (int i = 0; i < 2; i++) {
                        commonRobber.preInitResources();
//                    }
                }
                if (date.after(getStartTimeDate(user))) {
                    robClass.logger.info(this.getClass().getSimpleName() + "#结束抢公选预备资源检测!");
                    try {
                        initResourcesThread.shutdown();
                        if (!initResourcesThread.awaitTermination(5000, TimeUnit.MILLISECONDS)) {
                            initResourcesThread.shutdownNow();
                        }
                    } catch (InterruptedException e) {
                        robClass.logger.info("initResourcesThread - awaitTermination interrupted: " + e);
                        initResourcesThread.shutdownNow();
                    }
//                    this.cancel();
                } else {
                    robClass.logger.info(this.getClass().getSimpleName() + "#还未到定时抢公选课时间!");
                    robClass.logger.info(this.getClass().getSimpleName() + "#目前时间: " + date.toString());
                    robClass.logger.info(this.getClass().getSimpleName() + "#定时时间: " + getStartTimeDate(user));
                }
            }
        }, 0, 10, TimeUnit.SECONDS);
    }

    /**
     * 获取格式化开始时间
     */
    public Date getStartTimeDate(IUser user) {
        Date timestamp = null;
        try {
            timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(((RobUser) user).getStartTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return timestamp;
    }
}
